package com.xdja.study.mysql.dao;

import com.xdja.study.model.ErrorCodes;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.ResultSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class UserDaoVerticle extends AbstractVerticle {
    private static final Logger logger = LoggerFactory.getLogger(UserDaoVerticle.class);

    private JDBCClient jdbcClient;

    public void start(Future<Void> startFuture) throws Exception {
        //创建数据库客户端

        jdbcClient = JDBCClient.createShared(vertx, new JsonObject()
                .put("url", "jdbc:mysql://192.168.7.221:3306/dev_update")
//                .put("driver_class", "com.mysql.jdbc.Driver")
                .put("driver_class", "com.mysql.cj.jdbc.Driver")
                .put("max_pool_size", 30)
                .put("user", "update")
                .put("password", "manager"));

        jdbcClient.getConnection(conn -> {
            if(conn.failed()) {
                logger.error("从数据库获取用户信息失败：{}",  conn.cause().getMessage());
                startFuture.fail(conn.cause());
            } else {
                vertx.eventBus().consumer("user.dao", message -> {
                    String userId = message.headers().get("userId");
                    getUserFromDB(userId, message);
                });  // 注册事件监听
                logger.debug("user.dao监听事件注册完成");
            }

        });
    }

    private void getUserFromDB(String userId, Message<Object> message) {
        String sql = "select c_id, c_password, c_name from t_update_user where c_id = " + userId;
        jdbcClient.query(sql, res -> {
            if (res.succeeded()) {
                ResultSet resultSet = res.result();
                List<JsonObject> rows = resultSet.getRows();
                message.reply(new JsonObject().put("rows", rows));
            } else {
                reportQueryError(message, res.cause());
            }
        });
    }

    private void reportQueryError(Message<Object> message, Throwable cause) {
        logger.error("Database query error", cause);
        message.fail(ErrorCodes.DB_ERROR.ordinal(), cause.getMessage());
    }
}
